package han.chensing.latos.game.util;

import java.util.Arrays;

public class StopWatch {

    private final String[] labels;
    private final float[] times;
    private final int[] logTimes;
    private long lastTime;
    private long totTime;

    public StopWatch(int events){
        this.labels=new String[events];
        this.times=new float[events];
        this.logTimes=new int[events];
        this.totTime=0;
        Arrays.fill(this.times,0);
        Arrays.fill(logTimes,0);
    }

    public void start(){
        lastTime=System.nanoTime();
    }

    public void endAndStart(int targetIndex){
        long nowTime = System.nanoTime();
        float costTime = (nowTime - lastTime)/1000f;
        this.totTime+=costTime;
        this.times[targetIndex]+=costTime;
        this.logTimes[targetIndex]++;
        lastTime=nowTime;
    }

    public void print(){
        StringBuilder builder=new StringBuilder();
        builder.append("StopWatch - Cirno\n");
        builder.append("--------------------------\n");
        builder.append(" Name     AvrTime     Per \n");
        long totTimes=0;
        for (int i=0;i<labels.length;i++){
            String label = labels[i];
            float time = times[i];
            int logTime = logTimes[i];
            float vt = (time / (float) logTime);
            totTimes+=vt;
            builder
                    .append(label)
                    .append("\t")
                    .append(String.format("%.1fms",logTime==0?-1: vt))
                    .append("\t")
                    .append(String.format("%.1f%%",totTime==0?-1:((float)time/(float)totTime)*100f))
                    .append("\n");
        }
        builder.append("AvrPf:").append(totTimes).append("ms");
        System.out.println(builder.toString());
    }

    public String[] getLabels() {
        return labels;
    }
}
